﻿using System;
using System.Web;
using StyleMVVM.DependencyInjection;

namespace StyleMVVM.MVC.DependencyInjection
{
	public class WebSharedPerRequestContainer : ILifeCycleContainer
	{
		private string key;

		public WebSharedPerRequestContainer()
		{
			key = Guid.NewGuid().ToString();
		}

		public object RetrieveObject(IExportStrategy strategy,
		                             ExportLifeCycleMethod exportMethod,
		                             IDependencyInjectionContainer container,
		                             IInjectionContext injectionContext,
		                             object[] constructorParams)
		{
			object returnValue = HttpContext.Current.Items[key];

			if (returnValue == null)
			{
				IDisposalScope disposalScope = null;
				IDisposalScope oldScope = null;

				if (!strategy.ExternallyOwned)
				{
					disposalScope = HttpContext.Current.Items[DisposalScope.DisposalScopeStringKey] as IDisposalScope;

					if (disposalScope == null)
					{
						throw new Exception("DisposalScope is required for activating type " + strategy.ActivationType.FullName);
					}
					
					oldScope = injectionContext.DisposalScope;

					injectionContext.DisposalScope = disposalScope;
				}

				returnValue = exportMethod(injectionContext, constructorParams);

				if (oldScope != null)
				{
					injectionContext.DisposalScope = oldScope;
				}

				IDisposable disposable = returnValue as IDisposable;

				if (disposable != null && disposalScope != null)
				{
					disposalScope.AddObject(disposable);
				}

				HttpContext.Current.Items[key] = returnValue;
			}

			return returnValue;
		}

		public void Shutdown()
		{
			
		}
	}
}